﻿namespace HostsIt
{
	using System;
	using System.Globalization;
	using System.Threading;
	using System.Windows.Forms;

	internal static class Launcher
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		private static void Main()
		{
			#if !DEBUG
			using (System.Security.Principal.WindowsIdentity user = System.Security.Principal.WindowsIdentity.GetCurrent())
			{
				if (!(new System.Security.Principal.WindowsPrincipal(user).IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)))
				{
					MessageBox.Show(null, Resources.NoAccessGranted, Resources.ApplicationName,
					                MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
					return;
				}
			}
			#endif

			// setup unhandled exceptions handling
			AppDomain.CurrentDomain.UnhandledException += Launcher.CurrentDomainUnhandledException;

			// Set unhandled exceptions originating from Windows Froms to always route to ThreadException handler.
			Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
			Application.ThreadException += Launcher.ApplicationThreadException;

			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);

			Application.Run(new MainForm());
		}

		#region Unhandled excpetion handlers

		/// <summary>
		/// Occurs when an untrapped thread exception is thrown in Windows Forms threads.
		/// </summary>
		/// <param name="sender">The source of the unhandled exception event.</param>
		/// <param name="e">A <see cref="ThreadExceptionEventArgs"/> that contains the event data.</param>
		private static void ApplicationThreadException(Object sender, ThreadExceptionEventArgs e)
		{
			ShowGeneralErrorDialog(e.Exception);
		}

		/// <summary>
		/// Occurs when an exception is not caught in non-Windows Forms threads.
		/// </summary>
		/// <param name="sender">The source of the unhandled exception event.</param>
		/// <param name="e">An <see cref="UnhandledExceptionEventArgs"/> that contains the event data.</param>
		private static void CurrentDomainUnhandledException(Object sender, UnhandledExceptionEventArgs e)
		{
			ShowGeneralErrorDialog(e.ExceptionObject as Exception);
		}

		/// <summary>
		// Presents to a user a generalized error message.
		/// </summary>
		private static void ShowGeneralErrorDialog(Exception ex)
		{
			MessageBox.Show(String.Format(CultureInfo.CurrentCulture, ex.Message, Resources.ApplicationName),
			                Application.CompanyName,
			                MessageBoxButtons.OK,
			                MessageBoxIcon.Error,
			                MessageBoxDefaultButton.Button1,
			                MessageBoxOptions.DefaultDesktopOnly);
		}

		#endregion Unhandled excpetion handlers
	}
}